﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;
using Microsoft.SharePoint.Administration;
using System.Collections.ObjectModel;

namespace MicroLink.StsDev2008AddIn.BuildTasks
{
    public class DeploySolution : Task
    {
        #region SolutionName
        [Required()]
        public string SolutionName
        {
            get;
            set;
        }
        #endregion

        #region ForceDeploy
        public bool ForceDeploy
        {
            get;
            set;
        }
        #endregion

        #region AllowGacDeployment
        public bool AllowGacDeployment
        {
            get;
            set;
        }
        #endregion

        public override bool Execute()
        {
            bool deploySuccessful = true;

            SPSolution solution = SPFarm.Local.Solutions[SolutionName];
            if (solution != null)
            {
                if (!solution.Deployed)
                {
                    try
                    {
                        if (solution.ContainsWebApplicationResource)
                        {
                            Collection<SPWebApplication> webApplications = new Collection<SPWebApplication>();
                            foreach (SPWebApplication webApp in SPWebService.ContentService.WebApplications)
                                webApplications.Add(webApp);

                            solution.Deploy(DateTime.Now, AllowGacDeployment, webApplications, ForceDeploy);
                        }
                        else
                            solution.Deploy(DateTime.Now, AllowGacDeployment, ForceDeploy);
                    }
                    catch (Exception ex)
                    {
                        this.Log.LogError("Failed to deploy solution {0}. Exception: {1}", SolutionName, ex.Message);
                        deploySuccessful = false;
                    }
                }
            }
            else
                deploySuccessful = false;

            return deploySuccessful;
        }
    }
}
